from rest_framework import viewsets
from rest_framework import exceptions
from rest_framework.decorators import action

from datacenter.models import Entity
from datacenter.serializers import EntitySerializer
from datacenter.filters import EntityFilter
from connection.services import connection_service
from libs.decorators import required_query_parameters, permission_required
from libs.simple_responses import api_success
from libs.enums import Permission, LogModule
from log.services import log_service


class EntityViewSet(viewsets.ModelViewSet):
    queryset = Entity.objects.all()
    serializer_class = EntitySerializer
    filterset_class = EntityFilter
    ordering_fields = ('id',)
    log_module = LogModule.MODEL.value

    @permission_required([Permission.MODEL_MANAGE.value])
    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        super().perform_create(serializer)
        log_service.build_create_log(self.request.user, serializer.instance, self.log_module, f'创建了数据模型：{serializer.instance.name}')

    @permission_required([Permission.MODEL_MANAGE.value])
    def update(self, request, *args, **kwargs):
        return super().update(request, *args, **kwargs)

    @permission_required([Permission.MODEL_MANAGE.value])
    def partial_update(self, request, *args, **kwargs):
        return super().partial_update(request, *args, **kwargs)

    def perform_update(self, serializer):
        super().perform_update(serializer)
        log_service.build_update_log(self.request.user, serializer.instance, self.log_module, f'修改了数据模型：{serializer.instance.name}')

    @permission_required([Permission.MODEL_MANAGE.value])
    def destroy(self, request, *args, **kwargs):
        return super().destroy(request, *args, **kwargs)

    def perform_destroy(self, instance):
        super().perform_destroy(instance)
        log_service.build_update_log(self.request.user, instance, self.log_module, f'删除了数据模型：{instance.name}')

    @required_query_parameters(['connection_id'])
    @action(methods=['get'], detail=False, url_path='list-by-connection')
    def get_list_by_connection(self, request, *args, **kwargs):
        connection_id = request.query_params.get('connection_id')
        connection = connection_service.get_connection_by_id(connection_id)
        if not connection:
            raise exceptions.ParseError('未发现资源')
        certificate = connection_service.get_other_side_certificate(connection_id)
        if not certificate or not certificate.data:
            raise exceptions.ParseError('未建立互联关系')
        entities = certificate.data.get('entities')
        data = {
            'total': len(entities),
            'items': entities
        }
        return api_success(data=data)
